<template>
  <div class="volunteer-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <div class="title">
        <el-icon><User /></el-icon>
        <span>志愿者基础信息管理</span>
      </div>
      <div class="header-actions">
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          <el-icon><Delete /></el-icon>批量删除
        </el-button>
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增志愿者
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入姓名"
            clearable
            prefix-icon="Search"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        :empty-text="loading ? '加载中...' : '暂无数据'"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="姓名" width="120" align="center" />
        <el-table-column prop="idCard" label="身份证号" width="180" align="center" />
        <el-table-column prop="age" label="年龄" width="80" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row?.gender === '男' ? 'primary' : 'success'" effect="plain">
              {{ scope.row?.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" align="center" />
        <el-table-column prop="email" label="邮箱" width="180" align="center" />
        <el-table-column prop="volunteerNumber" label="志愿者编号" width="120" align="center" />
        <el-table-column prop="education" label="学历" width="100" align="center" />
        <el-table-column prop="occupation" label="职业" width="120" align="center" />
        <el-table-column prop="skills" label="技能特长" min-width="150" align="center" show-overflow-tooltip />
        <el-table-column prop="serviceHours" label="服务时长" width="100" align="center" />
        <el-table-column prop="address" label="居住地址" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row?.status)" effect="dark">
              {{ getStatusText(scope.row?.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="primary" link @click="handleView(scope.row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button 
              :type="scope.row?.status === 1 ? 'warning' : 'success'" 
              link 
              @click="handleStatusChange(scope.row)"
            >
              <el-icon><Switch /></el-icon>
              {{ scope.row?.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="isView"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="120" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="志愿者编号" prop="volunteerNumber">
          <el-input v-model="form.volunteerNumber" placeholder="请输入志愿者编号" />
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select v-model="form.education" placeholder="请选择学历">
            <el-option label="高中" value="高中" />
            <el-option label="专科" value="专科" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>
        <el-form-item label="职业" prop="occupation">
          <el-input v-model="form.occupation" placeholder="请输入职业" />
        </el-form-item>
        <el-form-item label="技能特长" prop="skills">
          <el-input v-model="form.skills" type="textarea" placeholder="请输入技能特长" />
        </el-form-item>
        <el-form-item label="服务时长" prop="serviceHours">
          <el-input-number v-model="form.serviceHours" :min="0" :max="9999" />
        </el-form-item>
        <el-form-item label="所在地区" required>
          <el-form-item prop="province" class="region-item">
            <el-select v-model="form.province" placeholder="请选择省份" @change="handleProvinceChange">
              <el-option
                v-for="item in provinceOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="city" class="region-item">
            <el-select v-model="form.city" placeholder="请选择城市" @change="handleCityChange">
              <el-option
                v-for="item in cityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item prop="district" class="region-item">
            <el-select v-model="form.district" placeholder="请选择区县">
              <el-option
                v-for="item in districtOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" v-if="!isView">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  User, 
  Plus, 
  Search, 
  Refresh, 
  Edit, 
  View, 
  Delete,
  Switch
} from '@element-plus/icons-vue'
import { 
  getVolunteerList, 
  addVolunteer, 
  updateVolunteer, 
  deleteVolunteer,
  batchDeleteVolunteer,
  updateVolunteerStatus,
  getVolunteerDetail
} from '@/api/volunteer'
import areaData from 'china-area-data'

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: null
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const isView = ref(false)

// 省市区数据
const provinceOptions = ref([])
const cityOptions = ref([])
const districtOptions = ref([])

// 表单数据
const form = reactive({
  id: '',
  name: '',
  idCard: '',
  age: 18,
  gender: '男',
  phone: '',
  email: '',
  volunteerNumber: '',
  education: '',
  occupation: '',
  skills: '',
  serviceHours: 0,
  province: '',
  city: '',
  district: '',
  address: '',
  status: 1
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  volunteerNumber: [{ required: true, message: '请输入志愿者编号', trigger: 'blur' }],
  education: [{ required: true, message: '请选择学历', trigger: 'change' }],
  occupation: [{ required: true, message: '请输入职业', trigger: 'blur' }],
  province: [{ required: true, message: '请选择省份', trigger: 'change' }],
  city: [{ required: true, message: '请选择城市', trigger: 'change' }],
  district: [{ required: true, message: '请选择区县', trigger: 'change' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '正常',
    2: '禁用'
  }
  return texts[status] || '未知'
}

// 获取志愿者列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    const res = await getVolunteerList(params)
    console.log('获取志愿者列表返回数据：', res)
    
    if (res.code === 200) {
      tableData.value = res.data?.list || []
      total.value = res.data?.total || 0
    } else {
      ElMessage.error(res.message || '获取志愿者列表失败')
    }
  } catch (error) {
    console.error('获取志愿者列表失败：', error)
    ElMessage.error('获取志愿者列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = null
  handleSearch()
}

// 表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  form.age = 18
  form.gender = '男'
  form.status = 1
  form.serviceHours = 0
  form.province = ''
  form.city = ''
  form.district = ''
  cityOptions.value = []
  districtOptions.value = []
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  isView.value = false
  resetForm()
}

// 新增志愿者
const handleAdd = () => {
  dialogTitle.value = '新增志愿者'
  dialogVisible.value = true
  isView.value = false
  resetForm()
}

// 编辑志愿者
const handleEdit = (row) => {
  dialogTitle.value = '编辑志愿者'
  dialogVisible.value = true
  isView.value = false
  Object.keys(form).forEach(key => {
    form[key] = row[key] || ''
  })
  // 触发省市区选择器的联动
  if (form.province) {
    handleProvinceChange(form.province)
    if (form.city) {
      handleCityChange(form.city)
    }
  }
}

// 初始化省市区数据
const initAreaData = () => {
  // 获取省份列表
  const provinces = areaData['86']
  provinceOptions.value = Object.entries(provinces).map(([code, name]) => ({
    value: code,
    label: name
  }))
}

// 获取城市列表
const fetchCityList = (provinceCode) => {
  const cities = areaData[provinceCode] || {}
  cityOptions.value = Object.entries(cities).map(([code, name]) => ({
    value: code,
    label: name
  }))
}

// 获取区县列表
const fetchDistrictList = (cityCode) => {
  const districts = areaData[cityCode] || {}
  districtOptions.value = Object.entries(districts).map(([code, name]) => ({
    value: code,
    label: name
  }))
}

// 处理省份变化
const handleProvinceChange = (value) => {
  form.city = ''
  form.district = ''
  cityOptions.value = []
  districtOptions.value = []
  if (value) {
    fetchCityList(value)
  }
}

// 处理城市变化
const handleCityChange = (value) => {
  form.district = ''
  districtOptions.value = []
  if (value) {
    fetchDistrictList(value)
  }
}

// 查看志愿者
const handleView = async (row) => {
  try {
    const res = await getVolunteerDetail(row.id)
    if (res.code === 200) {
      dialogTitle.value = '查看志愿者详情'
      dialogVisible.value = true
      isView.value = true
      Object.keys(form).forEach(key => {
        form[key] = res.data[key] || ''
      })
      // 触发省市区选择器的联动
      if (form.province) {
        await handleProvinceChange(form.province)
        if (form.city) {
          await handleCityChange(form.city)
        }
      }
    } else {
      ElMessage.error(res.message || '获取志愿者详情失败')
    }
  } catch (error) {
    console.error('获取志愿者详情失败：', error)
    ElMessage.error('获取志愿者详情失败')
  }
}

// 删除志愿者
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该志愿者信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteVolunteer(row.id)
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '删除志愿者失败')
      }
    } catch (error) {
      console.error('删除志愿者失败：', error)
      ElMessage.error('删除志愿者失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的志愿者')
    return
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条志愿者信息吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id).join(',')
      const res = await batchDeleteVolunteer(ids)
      if (res.code === 200) {
        ElMessage.success('批量删除成功')
        fetchData()
      } else {
        ElMessage.error(res.message || '批量删除志愿者失败')
      }
    } catch (error) {
      console.error('批量删除志愿者失败：', error)
      ElMessage.error('批量删除志愿者失败')
    }
  })
}

// 更新状态
const handleStatusChange = (row) => {
  const newStatus = row.status === 1 ? 2 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  ElMessageBox.confirm(`确认${statusText}该志愿者吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await updateVolunteerStatus(row.id, newStatus)
      if (res.code === 200) {
        ElMessage.success(`${statusText}成功`)
        fetchData()
      } else {
        ElMessage.error(res.message || `${statusText}志愿者失败`)
      }
    } catch (error) {
      console.error(`${statusText}志愿者失败：`, error)
      ElMessage.error(`${statusText}志愿者失败`)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.id) {
          res = await updateVolunteer(form.id, form)
        } else {
          res = await addVolunteer(form)
        }
        if (res.code === 200) {
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } else {
          ElMessage.error(res.message || '保存志愿者信息失败')
        }
      } catch (error) {
        console.error('保存志愿者信息失败：', error)
        ElMessage.error('保存志愿者信息失败')
      }
    }
  })
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 页面加载时获取数据
onMounted(() => {
  fetchData()
  initAreaData()
})
</script>

<style scoped>
.volunteer-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.title .el-icon {
  font-size: 28px;
  margin-right: 12px;
  color: #fff;
}

.search-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 24px;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.table-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.table-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin-top: 24px;
  display: flex;
  justify-content: flex-end;
  padding: 16px 0;
}

:deep(.el-table) {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #262626;
  font-weight: 600;
  padding: 16px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
  color: #595959;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.el-button--link) {
  padding: 0 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--link:hover) {
  transform: translateY(-1px);
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
}

:deep(.el-dialog__title) {
  color: #fff;
  font-weight: 600;
}

:deep(.el-dialog__body) {
  padding: 24px 32px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #262626;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #d9d9d9 inset;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #40a9ff inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #40a9ff inset;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 28px;
  line-height: 26px;
}

:deep(.el-pagination) {
  padding: 0;
}

:deep(.el-pagination .el-pagination__total) {
  margin-right: 16px;
}

:deep(.el-pagination .el-pagination__sizes) {
  margin-right: 16px;
}

:deep(.el-pagination .el-pager li) {
  border-radius: 4px;
  margin: 0 4px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .el-pager li.is-active) {
  background-color: #1890ff;
  color: #fff;
}

:deep(.el-pagination .el-pager li:not(.is-active):hover) {
  color: #1890ff;
}

:deep(.el-pagination .btn-prev),
:deep(.el-pagination .btn-next) {
  border-radius: 4px;
  transition: all 0.3s ease;
}

:deep(.el-pagination .btn-prev:hover),
:deep(.el-pagination .btn-next:hover) {
  color: #1890ff;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 24px;
}

:deep(.el-radio__label) {
  color: #595959;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #1890ff;
  border-color: #1890ff;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #1890ff;
}

.region-item {
  display: inline-block;
  margin-right: 16px;
  margin-bottom: 0;
}

.region-item:last-child {
  margin-right: 0;
}

:deep(.el-select) {
  width: 160px;
}

:deep(.el-form-item.is-required .el-form-item__label:before) {
  margin-right: 4px;
  color: #ff4d4f;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}

:deep(.el-form-item.is-required .el-form-item__label) {
  padding-right: 0;
}

:deep(.el-form-item.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-form-item.is-disabled .el-input__inner) {
  color: #606266;
}

:deep(.el-form-item.is-disabled .el-select .el-input__wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-form-item.is-disabled .el-select .el-input__inner) {
  color: #606266;
}

:deep(.el-form-item.is-disabled .el-radio__label) {
  color: #606266;
}

:deep(.el-form-item.is-disabled .el-textarea__inner) {
  background-color: #f5f7fa;
  color: #606266;
}
</style>
